package com.xiaozheng.decoupling.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Package: com.xiaozheng.decoupling.factory
 * @ClassName: BeanFactory
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/9/19 19:54
 * @What_is_this_file_for: 这个文件是用来做什么的?
 * @Description: 描述
 */
public class BeanFactory {

    private  static Properties props;

    //定义一个map用来存储要创建对象的容器
    private static Map<String ,Object> beans;

    static {
        try {
            //实例化对象
            props = new Properties();
            //获取properties文件的流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);

            //实例化容器
            beans = new HashMap<String, Object>();
            //取出配置文件中所有的K
            Enumeration<Object> keys = props.keys();

            //取出配置文件中所有的K法二
            {
                //获取map集合的所有键的set集合
                Set<Object> keySet = props.keySet();
                //获取其迭代器.（注意Set集合的类型要和迭代器保持一致）
                Iterator<Object> iterator = keySet.iterator();
                //判断集合里是不是已经没有元素了
                while (iterator.hasNext()) {
                    //迭代游标最开始是指向第一个元素的前面，如：-1位置
                    //取得当前集合的元素 然后把指针往后移一位指向下一个元素
                    System.out.println("iterator.next() = " + iterator.next());
                }
            }
            //遍历枚举
            while (keys.hasMoreElements()) {
                //取出每个key
                String key = keys.nextElement().toString();
                System.out.println("key = " + key);
                //根据key获取value
                String beanPath = props.getProperty(key);
                //反射创建对象,newInstance()实例化对象
                Object value = Class.forName(beanPath).newInstance();
                //把key，value存入容器
                beans.put(key, value);
            }

        } catch (IOException e) {
            throw new ExceptionInInitializerError("初始化properties失败！");
        } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据Bean名称获取bean对象
     * @param BeanName
     * @return
     */
    public static Object getBean(String BeanName){
        return beans.get(BeanName);
    }


    /*public static Object getBean(String BeanName){
        Object bean = null;
        try {
            String beanPath = props.getProperty(BeanName);
            bean = Class.forName(beanPath).newInstance();//每次都会调用默认构造函数创建对象
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return bean;
    }*/

}
